//
//  YLAHomeViewController.swift
//  Your Lover AI
//
//  Created by 阿忠 on 2024/6/18.
//

import Foundation
import UIKit
import SnapKit
import Alamofire
import CryptoKit
import SCrypto
import SwiftyJSON
import SDWebImage
import SVProgressHUD
import PopupDialog
import GoogleMobileAds
import FirebaseRemoteConfigInternal
import FirebaseAnalytics

class YLAHomeViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, GADFullScreenContentDelegate{
    
    var title_lb: UILabel!      // 标题
    
    var homeList_date = NSArray()
    
    var isUserStroe = false
    var isUserEvaluate = false
    
    var blurEffectView: UIVisualEffectView! = nil
    var ratingView: YLARatingView! = nil
    
    var indexInt: Int? = nil
    
    var remoteConfig: RemoteConfig!
    
    let loadingPhraseConfigKey = "appConfig"
    
    //插屏广告
    private var interstitial: GADInterstitialAd?
    
    lazy var bgImg: UIImageView = {
        let image = UIImageView(image: UIImage(named: "bg"))
        return image
    }()
    
    lazy var vipBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setImage(UIImage(named: "nav_vip 1"), for: UIControl.State.normal)
        button.addTarget(self, action: #selector(vipClick), for: .touchUpInside)
        return button
    }()
    
    private let AncientBookCellID = "YLAHomeCell"
    private let AncientBookHeadID = "AncientBookClassHead"
    
    lazy var classCollectView : UICollectionView = {
        //设置布局
        let kScreenWidth = UIScreen.main.bounds.size.width
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
        let itemSpac = (kScreenWidth) / 2
        layout.scrollDirection = .vertical //竖直
        layout.itemSize = CGSize.init(width: itemSpac - 20, height: 300)
        layout.minimumInteritemSpacing = 10 //item 间距
        layout.minimumLineSpacing = 13
        layout.sectionInset = .init(top: 10, left: 10, bottom: 5, right: 10)
        
        let collectView = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = .white.withAlphaComponent(0)
        collectView.showsVerticalScrollIndicator = false
        
        //注册cell、 header、 Footer
        collectView.register(YLAHomeCell.self, forCellWithReuseIdentifier: AncientBookCellID)
        
        view.addSubview(collectView)
        return collectView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tabBarController?.tabBar.backgroundColor = UIColor(hex: "AB23F8")
        self.view.backgroundColor = UIColor.green
        self.navigationController?.navigationBar.isHidden = true
        
        setUI()
        setRequest()
        //本地存储机器人信息
        storageRoleId()
        
    
        //正常进入首页 可以弹开屏广告
//        let userDefaults = UserDefaults.standard
//        userDefaults.set(true, forKey: "tostOpenAd")
        
        let userDefaults = UserDefaults.standard
//        self.isUserStroe = userDefaults.bool(forKey: "isUserStroe")
        self.isUserStroe = userDefaults.bool(forKey: "life") || userDefaults.bool(forKey: "year") ||  userDefaults.bool(forKey: "week")
        if !self.isUserStroe {//不是会员
            AppInterstitialManager.shared.showAdIfAvailable()
            AppRewardedManager.shared.showAdIfAvailable()
        }
        
    }
    
    //评分
    func ratingUI(){
        self.tabBarController!.tabBar.isHidden = true
        let blurEffect = UIBlurEffect(style: .light) // 可调整模糊效果的样式
        self.blurEffectView = UIVisualEffectView(effect: blurEffect)
        self.blurEffectView.frame = self.view.bounds
        self.view.addSubview(self.blurEffectView)
        
        let dialogFrame = CGRect(x: 0, y: 200, width: 270, height: 200)
        self.ratingView = YLARatingView(frame: dialogFrame, title: "续费", paymentMethod: "支付宝", paymentDescription: "请使用支付宝完成支付。")
        
        self.view.addSubview(self.ratingView)
        self.ratingView.snp.makeConstraints { make in
            make.centerY.centerY.equalToSuperview()
            make.left.equalTo(43)
            make.right.equalTo(-43)
            make.height.equalTo(256)
        }
        
        self.view.insertSubview(self.blurEffectView, belowSubview: self.ratingView)
        
        self.ratingView.onCancel = {
            // 执行取消操作
            self.tabBarController!.tabBar.isHidden = false
            self.ratingView.removeFromSuperview()
            self.blurEffectView.removeFromSuperview()
        }
        
        ratingView.onConfirm = { [self] text in
            if let startInt = text {
                self.tabBarController!.tabBar.isHidden = false
                self.ratingView.removeFromSuperview()
                self.blurEffectView.removeFromSuperview()
                if startInt <= 4 {
                    //弹窗提示
                    let popup = PopupDialog(title: "Notice", message: "thank you for your rating", image: nil)
                    self.present(popup, animated: true, completion: nil)
                }else{
                    //跳转到appstore评分
                    //购买成功  存储标识符
                    let userDefaults = UserDefaults.standard
                    userDefaults.set(true, forKey: "isUserEvaluate")
                    if let url = URL(string: "itms-apps://itunes.apple.com/app/id<6504508706>?action=write-review") {
                        if UIApplication.shared.canOpenURL(url) {
                            UIApplication.shared.open(url, options: [:], completionHandler: nil)
                        }
                    }
                }
            } else {
                print("取消了输入")
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.tabBarController!.tabBar.isHidden = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        

        let userDefaults = UserDefaults.standard
        
        //首次下载进入聊天框之后返回要弹
        var firstChat = userDefaults.integer(forKey: "isFirstChat")
        if firstChat == 1 {//第一次进入聊天页面返回  弹出评价框
            firstChat += 1
            userDefaults.set(firstChat, forKey: "isFirstChat")
            self.ratingUI()
        }
        
        //判定是否重置免费次数
        //先判断是否是会员
        /*
         UserDefaults.standard.set(true, forKey: "life")
         UserDefaults.standard.set(true, forKey: "year")
         UserDefaults.standard.set(true, forKey: "week")
         */
        self.isUserStroe = userDefaults.bool(forKey: "life") || userDefaults.bool(forKey: "year") ||  userDefaults.bool(forKey: "week")
        
//        self.isUserStroe = userDefaults.bool(forKey: "isUserStroe")
        if !self.isUserStroe {//不是会员
            //判断是否有存储过日期
            if let isUserTime = userDefaults.string(forKey: "isUserTime") {
                //                print(isUserTime)
                //在获取一次时间 作对比看是否要重置
                let newUserTime = self.currentMonthDayString()
                if newUserTime != isUserTime{//不同  重置免费次数
                    
                    remoteConfig = RemoteConfig.remoteConfig()
                    let str = remoteConfig[loadingPhraseConfigKey].stringValue
                    //                    print(str)
                    // 将字符串转换为Data
                    if let jsonData = str!.data(using: .utf8) {
                        // 尝试解析JSON数据
                        do {
                            // 解析JSON数据到字典
                            if let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                                let json = JSON.init(jsonDict)
                                let withAdUnitID = json["chatConfig"]["normalUserMsgCount"].stringValue
                                //                                  print(withAdUnitID)
                                print("-------------------获取成功了--------------")
                                
                                //激励视频提示文案
                                userDefaults.set("10", forKey: "isWatchCount")
                                userDefaults.set("3", forKey: "storeWeekCont")
                                userDefaults.set(withAdUnitID, forKey: "isUserFreeCount")
                                //将新的日期存起来
                                userDefaults.set(newUserTime, forKey: "isUserTime")
                            }
                        } catch {
                            print("解析错误: \(error.localizedDescription)")
                        }
                    }
                    
                    
                    
                }
                
            }else{//没有存过
                //存日期
                let isUserTime = self.currentMonthDayString()
                userDefaults.set(isUserTime, forKey: "isUserTime")
                
                remoteConfig = RemoteConfig.remoteConfig()
                let str = remoteConfig[loadingPhraseConfigKey].stringValue
                // 将字符串转换为Data
                if let jsonData = str!.data(using: .utf8) {
                    // 尝试解析JSON数据
                    do {
                        // 解析JSON数据到字典
                        if let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                            let json = JSON.init(jsonDict)
                            let withAdUnitID = json["chatConfig"]["normalUserMsgCount"].stringValue
                            //                              print(withAdUnitID)
                            print("-------------------获取成功了--------------")
                            //激励视频提示文案
                            userDefaults.set("10", forKey: "isWatchCount")
                            userDefaults.set("3", forKey: "storeWeekCont")
                            //存免费次数
                            userDefaults.set(withAdUnitID, forKey: "isUserFreeCount")
                            
                        }
                    } catch {
                        print("解析错误: \(error.localizedDescription)")
                    }
                }
                
                
                
            }
        }
        
    }
    

    
    func setUI() {
        
        view.addSubview(bgImg)
        bgImg.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        title_lb = UILabel()
        title_lb.textColor = .white
        title_lb.font = UIFont.boldSystemFont(ofSize: 25)
        title_lb.textAlignment = .left
        title_lb.text = "Your Lover AI"
        view.addSubview(title_lb)
        title_lb.snp.makeConstraints { make in
            make.left.equalTo(17)
            make.top.equalTo(55)
            make.height.equalTo(25)
        }
        
        
        view.addSubview(vipBtn)
        vipBtn.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.centerY.equalTo(title_lb)
            make.width.height.equalTo(36)
        }
        
        classCollectView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(title_lb.snp.bottom).offset(20)
            make.bottom.equalTo(-55)
        }
        
    }
    
    func setRequest() {
        
        let dataStr: String!
        
        let uuid = UUID().uuidString
        let userInfo: [String: Any] = [
            "userId": uuid,
            "userType": "1",
            "deviceType": "1"
        ]
        
        do {
            // 使用JSONSerialization将字典转换为Data
            let jsonData = try JSONSerialization.data(withJSONObject: userInfo, options: [])
            
            // jsonData已经是UTF-8编码的，因为JSONSerialization默认使用UTF-8
            // 如果你需要再次确认其是UTF-8编码，你可以这样做（但实际上不是必须的）
            if let utf8Data = String(data: jsonData, encoding: .utf8)?.data(using: .utf8) {
                // utf8Data 现在包含与 jsonData 相同的UTF-8编码的Data
                // 但这一步是多余的，因为 jsonData 已经是UTF-8了
            }
            
            //            print(jsonData)
            //            let plaintext = "plain text".data(using: String.Encoding.utf8)!
            let sharedSecretKey = "= cpfD4i3rkTA/xJMwOoFYrQ==".data(using: String.Encoding.utf8)!.SHA256() // AES-256
            let IV = try! Data.random(16) // Randomly generated IV. Length is equal to the AES block size(128)
            let ciphertext = try! jsonData.encrypt(.aes, options: .PKCS7Padding, key: sharedSecretKey, iv: IV)
            
            dataStr = dataToHexString(ciphertext)
            print(dataStr)
            
        } catch {
            // 处理JSON序列化过程中的任何错误
            print("Failed to serialize userInfo to JSON")
            return
        }
        
        
        
        let headers: HTTPHeaders = [
            "accept-encoding" : "gzip",
            "connection" : "Keep-Alive",
            "content-length" : "45",
            "Content-Type": "application/json",
            "data" :dataStr,
            "user-agent": "okhttp/4.10.0"
        ]
        
        let timestampMilliseconds = getCurrentTimestampMilliseconds()
        let parameters: [String: Any] = [
            "productId": "2",
            "timestamp": timestampMilliseconds
        ]
        SVProgressHUD.show()
//        Alamofire.request(YLARequest().robotListUrl, method: .post, parameters: parameters,encoding: JSONEncoding.default,headers: headers).responseJSON { response in
//            switch response.result {
//            case .success(let value):
//                SVProgressHUD.dismiss()
//                let json = JSON.init(value)
//                if json["code"].intValue != 200 {
//                    print(json["message"].stringValue)
//                    return
//                }
//                let tipcode = json["code"]
//                if let json = value as? [String: Any]{
//                    let tipCpde = json["code"] as? Int
//                    if tipCpde == 200 {//成功
//                        self.homeList_date = json["data"] as! NSArray
//                        
//                        //循环创建机器人数据  防止后续增加新的
//                        for i in 0..<self.homeList_date.count {
//                            let listData = self.homeList_date[i]
//                            let jsonObj = JSON.init(listData)
//                            let roleId = jsonObj["roleId"].stringValue
//                            if let retrievedData = UserDefaults.standard.data(forKey: roleId),
//                               var Roleid2 = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {
//                                
//                                //            print(Roleid2)
//                                
//                            } else {
//                                print("没有")
//                                // 定义一个字典数组
//                                let time = self.currentMonthDayHourMinuteString()
//                                let Role1_data: [[String: String]] = [
//                                    [
//                                        "coverUrl": "3425827518",
//                                        "name": "于明明",
//                                        "roleId": "18615782958",
//                                        "msgType": "1",
//                                        "msgContent": "Hi! Honey?",
//                                        "time": time
//                                    ]
//                                ]
//                                
//                                // 将字典数组编码为Data
//                                let encodedData = try? PropertyListEncoder().encode(Role1_data)
//                                
//                                // 使用UserDefaults存储Data
//                                UserDefaults.standard.set(encodedData, forKey: roleId)
//                            }
//                            
//                        }
//                        
//                        //                        print(self.homeList_date)
//                        self.classCollectView.reloadData()
//                    } else {
//                        let msgStr = json["msg"] as? String
//                        
//                        
//                    }
//                    
//                    
//                } else {
//                    SVProgressHUD.dismiss()
//                    print("Invalid JSON format or missing 'data' field")
//                }
//            case .failure(let error):
//                // 请求失败，处理错误信息
//                print("Error: \(error)")
//                SVProgressHUD.dismiss()
//            }
//        }
    }
    
    func storageRoleId(){
        
        let time = self.currentMonthDayHourMinuteString()
        // 从UserDefaults中检索是否有机器人信息
        if let retrievedData = UserDefaults.standard.data(forKey: "Roleid1"),
           var Roleid1 = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {
            
            //            print(Roleid1)
            
        } else {
            print("没有")
            // 定义一个字典数组
            let Role1_data: [[String: String]] = [
                [
                    "coverUrl": "3425827518",
                    "name": "于明明",
                    "roleId": "18615782958",
                    "msgType": "1",
                    "msgContent": "While she was arranging her nurse uniform, she turned to look at you and said,'Baby, have you had a good rest today?'",
                    "time": time
                ]
            ]
            
            // 将字典数组编码为Data
            let encodedData = try? PropertyListEncoder().encode(Role1_data)
            
            // 使用UserDefaults存储Data
            UserDefaults.standard.set(encodedData, forKey: "Roleid1")
        }
        
        if let retrievedData = UserDefaults.standard.data(forKey: "Roleid2"),
           var Roleid2 = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {
            
            //            print(Roleid2)
            
        } else {
            print("没有")
            // 定义一个字典数组
            let Role1_data: [[String: String]] = [
                [
                    "coverUrl": "3425827518",
                    "name": "于明明",
                    "roleId": "18615782958",
                    "msgType": "1",
                    "msgContent": "Sitting on a chair in the classroom, he looks at you affectionately and says, 'Teacher, what exciting knowledge are we going to learn today?'",
                    "time": time
                ]
            ]
            
            // 将字典数组编码为Data
            let encodedData = try? PropertyListEncoder().encode(Role1_data)
            
            // 使用UserDefaults存储Data
            UserDefaults.standard.set(encodedData, forKey: "Roleid2")
        }
        
        if let retrievedData = UserDefaults.standard.data(forKey: "Roleid3"),
           var Roleid3 = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {
            
            //            print(Roleid3)
            
        } else {
            print("没有")
            // 定义一个字典数组
            let Role3_data: [[String: String]] = [
                [
                    "coverUrl": "3425827518",
                    "name": "于明明",
                    "roleId": "18615782958",
                    "msgType": "1",
                    "msgContent": "Wearing sexy pajamas, she walks towards you slowly, ‘Baby, you're here, I've missed you for a long time.’",
                    "time": time
                ]
            ]
            
            // 将字典数组编码为Data
            let encodedData = try? PropertyListEncoder().encode(Role3_data)
            
            // 使用UserDefaults存储Data
            UserDefaults.standard.set(encodedData, forKey: "Roleid3")
        }
        
        if let retrievedData = UserDefaults.standard.data(forKey: "Roleid4"),
           var Roleid4 = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {
            
            //            print(Roleid4)
            
        } else {
            print("没有")
            // 定义一个字典数组
            let Role4_data: [[String: String]] = [
                [
                    "coverUrl": "3425827518",
                    "name": "于明明",
                    "roleId": "18615782958",
                    "msgType": "1",
                    "msgContent": "She was cleaning, looked back at you and said, ‘Master, what are your orders?’",
                    "time": time
                ]
            ]
            
            // 将字典数组编码为Data
            let encodedData = try? PropertyListEncoder().encode(Role4_data)
            
            // 使用UserDefaults存储Data
            UserDefaults.standard.set(encodedData, forKey: "Roleid4")
        }
        
        if let retrievedData = UserDefaults.standard.data(forKey: "Roleid5"),
           var Roleid5 = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {
            
            //            print(Roleid5)
            
        } else {
            print("没有")
            // 定义一个字典数组
            let Role5_data: [[String: String]] = [
                [
                    "coverUrl": "3425827518",
                    "name": "于明明",
                    "roleId": "18615782958",
                    "msgType": "1",
                    "msgContent": "When packing up the things needed for camping, I look back and say to you, “Baby, it’s my first time camping with you, I’m so excited.”’",
                    "time": time
                ]
            ]
            
            // 将字典数组编码为Data
            let encodedData = try? PropertyListEncoder().encode(Role5_data)
            
            // 使用UserDefaults存储Data
            UserDefaults.standard.set(encodedData, forKey: "Roleid5")
        }
        
        if let retrievedData = UserDefaults.standard.data(forKey: "Roleid6"),
           var Roleid6 = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {
            
            //            print(Roleid6)
            
        } else {
            print("没有")
            // 定义一个字典数组
            let Role6_data: [[String: String]] = [
                [
                    "coverUrl": "3425827518",
                    "name": "于明明",
                    "roleId": "18615782958",
                    "msgType": "1",
                    "msgContent": "On the busy street corner, she is eye to eye with you: “Can I meet you, this handsome man?“",
                    "time": time
                ]
            ]
            
            // 将字典数组编码为Data
            let encodedData = try? PropertyListEncoder().encode(Role6_data)
            
            // 使用UserDefaults存储Data
            UserDefaults.standard.set(encodedData, forKey: "Roleid6")
        }
        
        if let retrievedData = UserDefaults.standard.data(forKey: "Roleid7"),
           var Roleid6 = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {
            
            //            print(Roleid6)
            
        } else {
            print("没有")
            // 定义一个字典数组
            let Role6_data: [[String: String]] = [
                [
                    "coverUrl": "3425827518",
                    "name": "于明明",
                    "roleId": "18615782958",
                    "msgType": "1",
                    "msgContent": "Hi! Honey?",
                    "time": time
                ]
            ]
            
            // 将字典数组编码为Data
            let encodedData = try? PropertyListEncoder().encode(Role6_data)
            
            // 使用UserDefaults存储Data
            UserDefaults.standard.set(encodedData, forKey: "Roleid7")
        }
        
    }
    
    //获取当前的时间
    func currentMonthDayHourMinuteString() -> String {
        let dateFormatter = DateFormatter()
        // 设置日期格式，例如："MM月dd日 HH时mm分"
        dateFormatter.dateFormat = "MM.dd HH:mm"
        // 获取当前日期时间
        let now = Date()
        // 格式化日期时间
        let formattedDate = dateFormatter.string(from: now)
        // 返回格式化后的字符串
        return formattedDate
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.homeList_date.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AncientBookCellID, for: indexPath) as! YLAHomeCell
        let listData = self.homeList_date[indexPath.row]
        let jsonObj = JSON.init(listData)
        cell.nameLab.text = jsonObj["name"].stringValue
        cell.contentLab.text = jsonObj["introduce"].stringValue
        let imageUrl = jsonObj["coverUrl"].stringValue
        cell.iconImg.sd_setImage(with: URL(string: imageUrl), placeholderImage: UIImage(named: "home-rodia"))
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        indexInt = indexPath.row
        
//        if interstitial != nil {
//            interstitial!.present(fromRootViewController: nil)
//        }
        if !self.isUserStroe {//不是会员
            AppInterstitialManager.shared.showAdIfAvailable()
        }
        
        
        
        print("-----点击了首页的homecell--------")
        
        let listData = self.homeList_date[self.indexInt!]
        if self.indexInt == 0 {
            let talkVc = YLATalkViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if self.indexInt == 1 {
            let talkVc = YLATalk2ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if self.indexInt == 2{
            let talkVc = YLATalk3ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if self.indexInt == 3{
            let talkVc = YLATalk4ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if self.indexInt == 4{
            let talkVc = YLATalk5ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if self.indexInt == 5{
            let talkVc = YLATalk6ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else{
            let talkVc = YLATalk7ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleIdind = self.indexInt! + 1
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }
        
        
    }
    
    //    func loadRewardedAd() async {
    //        do {
    //             interstitial = try await GADInterstitialAd.load(
    //               withAdUnitID: "ca-app-pub-3940256099942544/4411468910", request: GADRequest())
    //             interstitial?.fullScreenContentDelegate = self
    //           } catch {
    //             print("Failed to load interstitial ad with error: \(error.localizedDescription)")
    //           }
    //    }
    
    /// Tells the delegate that the ad failed to present full screen content.
    //    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
    //      print("Ad did fail to present full screen content.")
    //    }
    //
    //    /// Tells the delegate that the ad will present full screen content.
    //    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
    //      print("插屏广告即将呈现")
    //    }
    //
    //    /// Tells the delegate that the ad dismissed full screen content.
    //    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
    //      print("插屏广告呈现完成")
    //
    //        let listData = self.homeList_date[self.indexInt!]
    //        if self.indexInt == 0 {
    //            let talkVc = YLATalkViewController()
    //            let jsonObj = JSON.init(listData)
    //            let roleId = jsonObj["roleId"].stringValue
    //            let roleName = jsonObj["name"].stringValue
    //            let roleCoverUrl = jsonObj["coverUrl"].stringValue
    //            talkVc.roleId = roleId
    //            talkVc.roleName = roleName
    //            talkVc.roleCoverUrl = roleCoverUrl
    //            self.navigationController?.pushViewController(talkVc, animated: true)
    //        }else if self.indexInt == 1 {
    //            let talkVc = YLATalk2ViewController()
    //            let jsonObj = JSON.init(listData)
    //            let roleId = jsonObj["roleId"].stringValue
    //            let roleName = jsonObj["name"].stringValue
    //            let roleCoverUrl = jsonObj["coverUrl"].stringValue
    //            talkVc.roleId = roleId
    //            talkVc.roleName = roleName
    //            talkVc.roleCoverUrl = roleCoverUrl
    //            self.navigationController?.pushViewController(talkVc, animated: true)
    //        }else if self.indexInt == 2{
    //            let talkVc = YLATalk3ViewController()
    //            let jsonObj = JSON.init(listData)
    //            let roleId = jsonObj["roleId"].stringValue
    //            let roleName = jsonObj["name"].stringValue
    //            let roleCoverUrl = jsonObj["coverUrl"].stringValue
    //            talkVc.roleId = roleId
    //            talkVc.roleName = roleName
    //            talkVc.roleCoverUrl = roleCoverUrl
    //            self.navigationController?.pushViewController(talkVc, animated: true)
    //        }else if self.indexInt == 3{
    //            let talkVc = YLATalk4ViewController()
    //            let jsonObj = JSON.init(listData)
    //            let roleId = jsonObj["roleId"].stringValue
    //            let roleName = jsonObj["name"].stringValue
    //            let roleCoverUrl = jsonObj["coverUrl"].stringValue
    //            talkVc.roleId = roleId
    //            talkVc.roleName = roleName
    //            talkVc.roleCoverUrl = roleCoverUrl
    //            self.navigationController?.pushViewController(talkVc, animated: true)
    //        }else if self.indexInt == 4{
    //            let talkVc = YLATalk5ViewController()
    //            let jsonObj = JSON.init(listData)
    //            let roleId = jsonObj["roleId"].stringValue
    //            let roleName = jsonObj["name"].stringValue
    //            let roleCoverUrl = jsonObj["coverUrl"].stringValue
    //            talkVc.roleId = roleId
    //            talkVc.roleName = roleName
    //            talkVc.roleCoverUrl = roleCoverUrl
    //            self.navigationController?.pushViewController(talkVc, animated: true)
    //        }else if self.indexInt == 5{
    //            let talkVc = YLATalk6ViewController()
    //            let jsonObj = JSON.init(listData)
    //            let roleId = jsonObj["roleId"].stringValue
    //            let roleName = jsonObj["name"].stringValue
    //            let roleCoverUrl = jsonObj["coverUrl"].stringValue
    //            talkVc.roleId = roleId
    //            talkVc.roleName = roleName
    //            talkVc.roleCoverUrl = roleCoverUrl
    //            self.navigationController?.pushViewController(talkVc, animated: true)
    //        }
    //
    //    }
    
    func getCurrentTimestampMilliseconds() -> Int64 {
        let date = Date()
        let timeInterval = date.timeIntervalSince1970
        return Int64(timeInterval * 1000)
    }
    
    func encrypt(text: String, key: SymmetricKey) -> Data {
        let data = text.data(using: .utf8)!
        let sealedBox = try! AES.GCM.seal(data, using: key)
        return sealedBox.combined!
    }
    
    func dataToHexString(_ data: Data) -> String {
        let hexChars = "0123456789ABCDEF"
        var hexString = ""
        
        for byte in data {
            hexString += String(format: "%02x", byte)
        }
        
        return hexString
    }
    
    func currentMonthDayString() -> String {
        // 获取当前日期
        let currentDate = Date()
        
        // 创建一个日期格式化器，并设置日期格式为 "MM-dd"
        let formatter = DateFormatter()
        formatter.dateFormat = "MM-dd"
        
        // 使用格式化器将日期转换为字符串
        let monthDayString = formatter.string(from: currentDate)
        
        // 返回月日字符串
        return monthDayString
    }
    
    @objc func vipClick(){
        let vipVc = YLAStroeViewControll()
        self.navigationController?.pushViewController(vipVc, animated: true)
    }
    
}
